package com.beecloud.learning.jackson.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: hengsun
 * Date: 3/29/17
 * Time: 3:31 PM
 * Description:
 */
public class JacksonUtil {

    public static <T> String toSnakeJson(T target) throws JsonProcessingException {
        return toJson(target, PropertyNamingStrategy.SNAKE_CASE);
    }

    public static <T> T parserSnakeJson(String jsonStr, Class<T> target) throws IOException {
        return parserJson(jsonStr, target, PropertyNamingStrategy.SNAKE_CASE);
    }


    public static <T> String toUpperCamelJson(T target) throws JsonProcessingException {
        return toJson(target, PropertyNamingStrategy.UPPER_CAMEL_CASE);
    }

    public static <T> T parserUpperCamelJson(String jsonStr, Class<T> target) throws IOException {
        return parserJson(jsonStr, target, PropertyNamingStrategy.UPPER_CAMEL_CASE);
    }


    private static <T> String toJson(T target, PropertyNamingStrategy namingStrategy) throws JsonProcessingException {
        ObjectMapper objectMapper = getObejectMapper(namingStrategy);
        return objectMapper.writeValueAsString(target);
    }

    private static <T> T parserJson(String jsonStr, Class<T> target, PropertyNamingStrategy namingStrategy) throws IOException {
        ObjectMapper objectMapper = getObejectMapper(namingStrategy);
        return objectMapper.readValue(jsonStr, target);
    }


    private static ObjectMapper getObejectMapper(PropertyNamingStrategy namingStrategy) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(namingStrategy);
        return objectMapper;
    }

}
